package com.zf.spring.microservice.zuul.common.filters.error;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zf.spring.microservice.zuul.common.ResponseMessage;
import com.zf.spring.microservice.zuul.common.filters.FilterConfigurationBean;

@Component
public class SendErrorResFilter extends ZuulFilter {
	FilterConfigurationBean filterConfigurationBean;

	public SendErrorResFilter(FilterConfigurationBean filterConfigurationBean) {
		super();
		this.filterConfigurationBean = filterConfigurationBean;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		String status = String.valueOf(context.getResponseStatusCode());
		String meesage = filterConfigurationBean
				.getMessageByErrorStatus(status);
		String content = JSONObject.toJSONString(new ResponseMessage(false,
				meesage));
		context.setResponseGZipped(false);
		context.setResponseDataStream(IOUtils.toInputStream(content, Charsets.UTF_8));
		return null;
	}

	@Override
	public String filterType() {
		return "error";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
